package com.hmkj.core.service.invest.impl;

import com.hmkj.common.baseMapper.GenericMapper;
import com.hmkj.common.baseMapper.GenericPo;
import com.hmkj.common.utils.DateUtils;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.invest.InvestMapper;
import com.hmkj.core.mapper.investAccountLog.InvestAccountLogMapper;
import com.hmkj.core.po.invest.Invest;
import com.hmkj.core.po.investAccountLog.InvestAccountLog;
import com.hmkj.core.service.invest.InvestService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 投资人表业务相关Service接口实现<br>
 *
 * @ClassName: InvestServiceImpl
 * @author lizhijie
 * @date   2018-07-05 11:19:19
 */
@Service
@Scope("prototype")
@Transactional(rollbackFor = Exception.class)
public class InvestServiceImpl implements InvestService {

	@Resource
    private InvestMapper investMapper;
	@Resource
    private InvestAccountLogMapper investAccountLogMapper;

    @Override
    public GenericMapper<Invest,Integer> _getMapper() {
        return investMapper;
    }

    @Override
    public void editInvestAccount(Invest newInvest,Integer type) throws Exception{

        Invest invest = investMapper.selectByPrimaryKey(newInvest.getId());
        BigDecimal amount = BigDecimal.ZERO;
        if(1 == type){
            amount = newInvest.getInvestAccount().add(invest.getInvestAccount());
        }
        if(2 == type) {
            if(((newInvest.getInvestAccount().negate()).add(invest.getInvestAccount())).compareTo(BigDecimal.ZERO) == -1){
                throw new BussinessException("余额不足");
            }
            else {
                amount = invest.getInvestAccount().add(newInvest.getInvestAccount().negate());
            }
        }
        invest.setInvestAccount(amount);
        investMapper.updateByPrimaryKeySelective(invest);
        InvestAccountLog investAccountLog = new InvestAccountLog();
        investAccountLog.setUserId(invest.getUserId());
        investAccountLog.setInvestId(invest.getId());
        if (newInvest.getInvestAccount().compareTo(BigDecimal.ZERO)== -1){
            investAccountLog.setDirection(InvestAccountLog.DIRECTION.T1.code);
        }else {
            investAccountLog.setDirection(InvestAccountLog.DIRECTION.T2.code);
        }
        investAccountLog.setAmount(newInvest.getInvestAccount());
        investAccountLog.setAcocuntLeft(amount);
        investAccountLog.setRemark("调整偏差");
        investAccountLog.setDelFlag(InvestAccountLog.DELFLAG.NORMAL.code);
        investAccountLog.setCreateTime(DateUtils.getNow());
        investAccountLogMapper.updateByPrimaryKeySelective(investAccountLog);
    }
}
